package com.imti.service.impl;

import com.imti.mapper.QuestMapper;
import com.imti.model.Answer;
import com.imti.model.Quest;
import com.imti.service.QuestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class QuestServiceImpl implements QuestService {
    @Autowired
    private QuestMapper questMapper;


    @Override
    public List<Quest> findAllQuest(Integer id) {
        return questMapper.findAllQuest(id);
    }

    @Override
    public List<Quest> findByQuest(Quest quest) {
        return questMapper.findByQuest(quest);
    }


    @Override
    @Transactional //事务
    public boolean saveQuestionAnswer(Quest quest) {
        try{
            //#1、添加题目表
            int res=questMapper.saveQuestion(quest);
            //获取最新插入的问题id?
            int questionId=questMapper.getMaxQuestionId();
            //2、保存题目和题库的关系
            quest.setId(questionId);
            int res2=questMapper.saveQuestionRepo(quest);
            if(!"3".equals(quest.getType())) {
                // #3、添加答案表（多条、判断题不需要添加）
                String[] contexts = quest.getContexts();
                String[] iscorrs = quest.getCorrectFlag();
                for (int i = 0; i < contexts.length; i++) {
                    Answer answer = new Answer();
                    answer.setQuestionId(questionId);
                    answer.setContext(contexts[i]);
                    answer.setCorrectFlag(iscorrs[i]);
                    int res1 = questMapper.saveAnswer(answer);
                }
//        #4、找出正确答案
                String answerIds = questMapper.saveQuestionAnswerId(questionId + "");
//        #5、更新题目中答案id
                quest.setAnswerId(answerIds);
                int res3 = questMapper.updateQuestionAnswerId(quest);
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

}
